﻿using System.Web;
using System.Text.RegularExpressions;
using WebConversion.Common.Configuration;

namespace WebConversion.Common.UrlRewriter
{
    public class AggregationUrlRewriter : UrlRewriterBase
    {
        protected override void Rewrite(string requestedPath, HttpApplication context)
        {
            // 获得配置规则
            var ruleCollection = AppConfigReader.GetRewriterRules();

            // 遍历每个规则
            foreach (var rule in ruleCollection.RewriterRules)
            {
                // 获得要查找的模式，并解析 Url（转换为相应的目录）
                var lookFor =
                    "^"
                    + ResolveUrl(context.Context.Request.ApplicationPath, rule.LookFor)
                    + "$";

                // 创建 regex(请注意，已设置 IgnoreCase...)
                var regex = new Regex(lookFor, RegexOptions.IgnoreCase);

                // 是否找到了匹配的规则
                if (!regex.IsMatch(requestedPath)) continue;

                // 找到了匹配的规则 -- 进行必要的替换
                var sendToUrl =
                    ResolveUrl(context.Context.Request.ApplicationPath,
                               regex.Replace(requestedPath, rule.SendTo));

                // 重写 URL
                RewriteUrl(context, sendToUrl);
                break;
            }
        }

        public static string ResolveUrl(string lookFor)
        {
            return ResolveUrl(HttpContext.Current.Request.ApplicationPath, lookFor);
        }

        private static string ResolveUrl(string applicationPath, string lookFor)
        {
            return applicationPath + lookFor;
        }

        private static void RewriteUrl(HttpApplication context, string sendToUrl)
        {
            context.Context.RewritePath(sendToUrl);
        }
    }
}
